home *** CD-ROM | disk | FTP | other *** search
/ Personal Computer World 2007 September / PCWSEP07.iso / Software / Linux / Linux Mint 3.0 Light / LinuxMint-3.0-Light.iso / casper / filesystem.squashfs / usr / lib / python2.4 / test / regrtest.py < prev    next >
Encoding:
Python Source  |  2007-04-12  |  35.6 KB  |  1,198 lines

  1. #! /usr/bin/python2.4
  2.  
  3. """Regression test.
  4.  
  5. This will find all modules whose name is "test_*" in the test
  6. directory, and run them.  Various command line options provide
  7. additional facilities.
  8.  
  9. Command line options:
  10.  
  11. -v: verbose    -- run tests in verbose mode with output to stdout
  12. -w: verbose2   -- re-run failed tests in verbose mode
  13. -q: quiet      -- don't print anything except if a test fails
  14. -g: generate   -- write the output file for a test instead of comparing it
  15. -x: exclude    -- arguments are tests to *exclude*
  16. -s: single     -- run only a single test (see below)
  17. -r: random     -- randomize test execution order
  18. -f: fromfile   -- read names of tests to run from a file (see below)
  19. -l: findleaks  -- if GC is available detect tests that leak memory
  20. -u: use        -- specify which special resource intensive tests to run
  21. -h: help       -- print this text and exit
  22. -t: threshold  -- call gc.set_threshold(N)
  23. -T: coverage   -- turn on code coverage using the trace module
  24. -D: coverdir   -- Directory where coverage files are put
  25. -N: nocoverdir -- Put coverage files alongside modules
  26. -L: runleaks   -- run the leaks(1) command just before exit
  27. -R: huntrleaks -- search for reference leaks (needs debug build, v. slow)
  28.  
  29. If non-option arguments are present, they are names for tests to run,
  30. unless -x is given, in which case they are names for tests not to run.
  31. If no test names are given, all tests are run.
  32.  
  33. -v is incompatible with -g and does not compare test output files.
  34.  
  35. -T turns on code coverage tracing with the trace module.
  36.  
  37. -D specifies the directory where coverage files are put.
  38.  
  39. -N Put coverage files alongside modules.
  40.  
  41. -s means to run only a single test and exit.  This is useful when
  42. doing memory analysis on the Python interpreter (which tend to consume
  43. too many resources to run the full regression test non-stop).  The
  44. file /tmp/pynexttest is read to find the next test to run.  If this
  45. file is missing, the first test_*.py file in testdir or on the command
  46. line is used.  (actually tempfile.gettempdir() is used instead of
  47. /tmp).
  48.  
  49. -f reads the names of tests from the file given as f's argument, one
  50. or more test names per line.  Whitespace is ignored.  Blank lines and
  51. lines beginning with '#' are ignored.  This is especially useful for
  52. whittling down failures involving interactions among tests.
  53.  
  54. -L causes the leaks(1) command to be run just before exit if it exists.
  55. leaks(1) is available on Mac OS X and presumably on some other
  56. FreeBSD-derived systems.
  57.  
  58. -R runs each test several times and examines sys.gettotalrefcount() to
  59. see if the test appears to be leaking references.  The argument should
  60. be of the form stab:run:fname where 'stab' is the number of times the
  61. test is run to let gettotalrefcount settle down, 'run' is the number
  62. of times further it is run and 'fname' is the name of the file the
  63. reports are written to.  These parameters all have defaults (5, 4 and
  64. "reflog.txt" respectively), so the minimal invocation is '-R ::'.
  65.  
  66. -u is used to specify which special resource intensive tests to run,
  67. such as those requiring large file support or network connectivity.
  68. The argument is a comma-separated list of words indicating the
  69. resources to test.  Currently only the following are defined:
  70.  
  71.     all -       Enable all special resources.
  72.  
  73.     audio -     Tests that use the audio device.  (There are known
  74.                 cases of broken audio drivers that can crash Python or
  75.                 even the Linux kernel.)
  76.  
  77.     curses -    Tests that use curses and will modify the terminal's
  78.                 state and output modes.
  79.  
  80.     largefile - It is okay to run some test that may create huge
  81.                 files.  These tests can take a long time and may
  82.                 consume >2GB of disk space temporarily.
  83.  
  84.     network -   It is okay to run tests that use external network
  85.                 resource, e.g. testing SSL support for sockets.
  86.  
  87.     bsddb -     It is okay to run the bsddb testsuite, which takes
  88.                 a long time to complete.
  89.  
  90.     decimal -   Test the decimal module against a large suite that
  91.                 verifies compliance with standards.
  92.  
  93.     compiler -  Test the compiler package by compiling all the source
  94.                 in the standard library and test suite.  This takes
  95.                 a long time.
  96.  
  97.     subprocess  Run all tests for the subprocess module.
  98.  
  99. To enable all resources except one, use '-uall,-<resource>'.  For
  100. example, to run all the tests except for the bsddb tests, give the
  101. option '-uall,-bsddb'.
  102. """
  103.  
  104. import os
  105. import sys
  106. import getopt
  107. import random
  108. import warnings
  109. import sre
  110. import cStringIO
  111. import traceback
  112.  
  113. # I see no other way to suppress these warnings;
  114. # putting them in test_grammar.py has no effect:
  115. warnings.filterwarnings("ignore", "hex/oct constants", FutureWarning,
  116.                         ".*test.test_grammar$")
  117. if sys.maxint > 0x7fffffff:
  118.     # Also suppress them in <string>, because for 64-bit platforms,
  119.     # that's where test_grammar.py hides them.
  120.     warnings.filterwarnings("ignore", "hex/oct constants", FutureWarning,
  121.                             "<string>")
  122.  
  123. # MacOSX (a.k.a. Darwin) has a default stack size that is too small
  124. # for deeply recursive regular expressions.  We see this as crashes in
  125. # the Python test suite when running test_re.py and test_sre.py.  The
  126. # fix is to set the stack limit to 2048.
  127. # This approach may also be useful for other Unixy platforms that
  128. # suffer from small default stack limits.
  129. if sys.platform == 'darwin':
  130.     try:
  131.         import resource
  132.     except ImportError:
  133.         pass
  134.     else:
  135.         soft, hard = resource.getrlimit(resource.RLIMIT_STACK)
  136.         newsoft = min(hard, max(soft, 1024*2048))
  137.         resource.setrlimit(resource.RLIMIT_STACK, (newsoft, hard))
  138.  
  139. from test import test_support
  140.  
  141. RESOURCE_NAMES = ('audio', 'curses', 'largefile', 'network', 'bsddb',
  142.                   'decimal', 'compiler', 'subprocess')
  143.  
  144.  
  145. def usage(code, msg=''):
  146.     print __doc__
  147.     if msg: print msg
  148.     sys.exit(code)
  149.  
  150.  
  151. def main(tests=None, testdir=None, verbose=0, quiet=False, generate=False,
  152.          exclude=False, single=False, randomize=False, fromfile=None,
  153.          findleaks=False, use_resources=None, trace=False, coverdir='coverage',
  154.          runleaks=False, huntrleaks=False, verbose2=False):
  155.     """Execute a test suite.
  156.  
  157.     This also parses command-line options and modifies its behavior
  158.     accordingly.
  159.  
  160.     tests -- a list of strings containing test names (optional)
  161.     testdir -- the directory in which to look for tests (optional)
  162.  
  163.     Users other than the Python test suite will certainly want to
  164.     specify testdir; if it's omitted, the directory containing the
  165.     Python test suite is searched for.
  166.  
  167.     If the tests argument is omitted, the tests listed on the
  168.     command-line will be used.  If that's empty, too, then all *.py
  169.     files beginning with test_ will be used.
  170.  
  171.     The other default arguments (verbose, quiet, generate, exclude, single,
  172.     randomize, findleaks, use_resources, trace and coverdir) allow programmers
  173.     calling main() directly to set the values that would normally be set by
  174.     flags on the command line.
  175.     """
  176.  
  177.     test_support.record_original_stdout(sys.stdout)
  178.     try:
  179.         opts, args = getopt.getopt(sys.argv[1:], 'hvgqxsrf:lu:t:TD:NLR:w',
  180.                                    ['help', 'verbose', 'quiet', 'generate',
  181.                                     'exclude', 'single', 'random', 'fromfile',
  182.                                     'findleaks', 'use=', 'threshold=', 'trace',
  183.                                     'coverdir=', 'nocoverdir', 'runleaks',
  184.                                     'huntrleaks=', 'verbose2',
  185.                                     ])
  186.     except getopt.error, msg:
  187.         usage(2, msg)
  188.  
  189.     # Defaults
  190.     if use_resources is None:
  191.         use_resources = []
  192.     for o, a in opts:
  193.         if o in ('-h', '--help'):
  194.             usage(0)
  195.         elif o in ('-v', '--verbose'):
  196.             verbose += 1
  197.         elif o in ('-w', '--verbose2'):
  198.             verbose2 = True
  199.         elif o in ('-q', '--quiet'):
  200.             quiet = True;
  201.             verbose = 0
  202.         elif o in ('-g', '--generate'):
  203.             generate = True
  204.         elif o in ('-x', '--exclude'):
  205.             exclude = True
  206.         elif o in ('-s', '--single'):
  207.             single = True
  208.         elif o in ('-r', '--randomize'):
  209.             randomize = True
  210.         elif o in ('-f', '--fromfile'):
  211.             fromfile = a
  212.         elif o in ('-l', '--findleaks'):
  213.             findleaks = True
  214.         elif o in ('-L', '--runleaks'):
  215.             runleaks = True
  216.         elif o in ('-t', '--threshold'):
  217.             import gc
  218.             gc.set_threshold(int(a))
  219.         elif o in ('-T', '--coverage'):
  220.             trace = True
  221.         elif o in ('-D', '--coverdir'):
  222.             coverdir = os.path.join(os.getcwd(), a)
  223.         elif o in ('-N', '--nocoverdir'):
  224.             coverdir = None
  225.         elif o in ('-R', '--huntrleaks'):
  226.             huntrleaks = a.split(':')
  227.             if len(huntrleaks) != 3:
  228.                 print a, huntrleaks
  229.                 usage(2, '-R takes three colon-separated arguments')
  230.             if len(huntrleaks[0]) == 0:
  231.                 huntrleaks[0] = 5
  232.             else:
  233.                 huntrleaks[0] = int(huntrleaks[0])
  234.             if len(huntrleaks[1]) == 0:
  235.                 huntrleaks[1] = 4
  236.             else:
  237.                 huntrleaks[1] = int(huntrleaks[1])
  238.             if len(huntrleaks[2]) == 0:
  239.                 huntrleaks[2] = "reflog.txt"
  240.         elif o in ('-u', '--use'):
  241.             u = [x.lower() for x in a.split(',')]
  242.             for r in u:
  243.                 if r == 'all':
  244.                     use_resources[:] = RESOURCE_NAMES
  245.                     continue
  246.                 remove = False
  247.                 if r[0] == '-':
  248.                     remove = True
  249.                     r = r[1:]
  250.                 if r not in RESOURCE_NAMES:
  251.                     usage(1, 'Invalid -u/--use option: ' + a)
  252.                 if remove:
  253.                     if r in use_resources:
  254.                         use_resources.remove(r)
  255.                 elif r not in use_resources:
  256.                     use_resources.append(r)
  257.     if generate and verbose:
  258.         usage(2, "-g and -v don't go together!")
  259.     if single and fromfile:
  260.         usage(2, "-s and -f don't go together!")
  261.  
  262.     good = []
  263.     bad = []
  264.     skipped = []
  265.     resource_denieds = []
  266.  
  267.     if findleaks:
  268.         try:
  269.             import gc
  270.         except ImportError:
  271.             print 'No GC available, disabling findleaks.'
  272.             findleaks = False
  273.         else:
  274.             # Uncomment the line below to report garbage that is not
  275.             # freeable by reference counting alone.  By default only
  276.             # garbage that is not collectable by the GC is reported.
  277.             #gc.set_debug(gc.DEBUG_SAVEALL)
  278.             found_garbage = []
  279.  
  280.     if single:
  281.         from tempfile import gettempdir
  282.         filename = os.path.join(gettempdir(), 'pynexttest')
  283.         try:
  284.             fp = open(filename, 'r')
  285.             next = fp.read().strip()
  286.             tests = [next]
  287.             fp.close()
  288.         except IOError:
  289.             pass
  290.  
  291.     if fromfile:
  292.         tests = []
  293.         fp = open(fromfile)
  294.         for line in fp:
  295.             guts = line.split() # assuming no test has whitespace in its name
  296.             if guts and not guts[0].startswith('#'):
  297.                 tests.extend(guts)
  298.         fp.close()
  299.  
  300.     # Strip .py extensions.
  301.     if args:
  302.         args = map(removepy, args)
  303.     if tests:
  304.         tests = map(removepy, tests)
  305.  
  306.     stdtests = STDTESTS[:]
  307.     nottests = NOTTESTS[:]
  308.     if exclude:
  309.         for arg in args:
  310.             if arg in stdtests:
  311.                 stdtests.remove(arg)
  312.         nottests[:0] = args
  313.         args = []
  314.     tests = tests or args or findtests(testdir, stdtests, nottests)
  315.     if single:
  316.         tests = tests[:1]
  317.     if randomize:
  318.         random.shuffle(tests)
  319.     if trace:
  320.         import trace
  321.         tracer = trace.Trace(ignoredirs=[sys.prefix, sys.exec_prefix],
  322.                              trace=False, count=True)
  323.     test_support.verbose = verbose      # Tell tests to be moderately quiet
  324.     test_support.use_resources = use_resources
  325.     save_modules = sys.modules.keys()
  326.     for test in tests:
  327.         if not quiet:
  328.             print test
  329.             sys.stdout.flush()
  330.         if trace:
  331.             # If we're tracing code coverage, then we don't exit with status
  332.             # if on a false return value from main.
  333.             tracer.runctx('runtest(test, generate, verbose, quiet, testdir)',
  334.                           globals=globals(), locals=vars())
  335.         else:
  336.             ok = runtest(test, generate, verbose, quiet, testdir, huntrleaks)
  337.             if ok > 0:
  338.                 good.append(test)
  339.             elif ok == 0:
  340.                 bad.append(test)
  341.             else:
  342.                 skipped.append(test)
  343.                 if ok == -2:
  344.                     resource_denieds.append(test)
  345.         if findleaks:
  346.             gc.collect()
  347.             if gc.garbage:
  348.                 print "Warning: test created", len(gc.garbage),
  349.                 print "uncollectable object(s)."
  350.                 # move the uncollectable objects somewhere so we don't see
  351.                 # them again
  352.                 found_garbage.extend(gc.garbage)
  353.                 del gc.garbage[:]
  354.         # Unload the newly imported modules (best effort finalization)
  355.         for module in sys.modules.keys():
  356.             if module not in save_modules and module.startswith("test."):
  357.                 test_support.unload(module)
  358.  
  359.     # The lists won't be sorted if running with -r
  360.     good.sort()
  361.     bad.sort()
  362.     skipped.sort()
  363.  
  364.     if good and not quiet:
  365.         if not bad and not skipped and len(good) > 1:
  366.             print "All",
  367.         print count(len(good), "test"), "OK."
  368.         if verbose:
  369.             print "CAUTION:  stdout isn't compared in verbose mode:"
  370.             print "a test that passes in verbose mode may fail without it."
  371.     if bad:
  372.         print count(len(bad), "test"), "failed:"
  373.         printlist(bad)
  374.     if skipped and not quiet:
  375.         print count(len(skipped), "test"), "skipped:"
  376.         printlist(skipped)
  377.  
  378.         e = _ExpectedSkips()
  379.         plat = sys.platform
  380.         if e.isvalid():
  381.             surprise = set(skipped) - e.getexpected() - set(resource_denieds)
  382.             if surprise:
  383.                 print count(len(surprise), "skip"), \
  384.                       "unexpected on", plat + ":"
  385.                 printlist(surprise)
  386.             else:
  387.                 print "Those skips are all expected on", plat + "."
  388.         else:
  389.             print "Ask someone to teach regrtest.py about which tests are"
  390.             print "expected to get skipped on", plat + "."
  391.  
  392.     if verbose2 and bad:
  393.         print "Re-running failed tests in verbose mode"
  394.         for test in bad:
  395.             print "Re-running test %r in verbose mode" % test
  396.             sys.stdout.flush()
  397.             try:
  398.                 test_support.verbose = 1
  399.                 ok = runtest(test, generate, 1, quiet, testdir,
  400.                              huntrleaks)
  401.             except KeyboardInterrupt:
  402.                 # print a newline separate from the ^C
  403.                 print
  404.                 break
  405.             except:
  406.                 raise
  407.  
  408.     if single:
  409.         alltests = findtests(testdir, stdtests, nottests)
  410.         for i in range(len(alltests)):
  411.             if tests[0] == alltests[i]:
  412.                 if i == len(alltests) - 1:
  413.                     os.unlink(filename)
  414.                 else:
  415.                     fp = open(filename, 'w')
  416.                     fp.write(alltests[i+1] + '\n')
  417.                     fp.close()
  418.                 break
  419.         else:
  420.             os.unlink(filename)
  421.  
  422.     if trace:
  423.         r = tracer.results()
  424.         r.write_results(show_missing=True, summary=True, coverdir=coverdir)
  425.  
  426.     if runleaks:
  427.         os.system("leaks %d" % os.getpid())
  428.  
  429.     sys.exit(len(bad) > 0)
  430.  
  431.  
  432. STDTESTS = [
  433.     'test_grammar',
  434.     'test_opcodes',
  435.     'test_operations',
  436.     'test_builtin',
  437.     'test_exceptions',
  438.     'test_types',
  439.    ]
  440.  
  441. NOTTESTS = [
  442.     'test_support',
  443.     'test_future1',
  444.     'test_future2',
  445.     'test_future3',
  446.     ]
  447.  
  448. def findtests(testdir=None, stdtests=STDTESTS, nottests=NOTTESTS):
  449.     """Return a list of all applicable test modules."""
  450.     if not testdir: testdir = findtestdir()
  451.     names = os.listdir(testdir)
  452.     tests = []
  453.     for name in names:
  454.         if name[:5] == "test_" and name[-3:] == os.extsep+"py":
  455.             modname = name[:-3]
  456.             if modname not in stdtests and modname not in nottests:
  457.                 tests.append(modname)
  458.     tests.sort()
  459.     return stdtests + tests
  460.  
  461. def runtest(test, generate, verbose, quiet, testdir=None, huntrleaks=False):
  462.     """Run a single test.
  463.     test -- the name of the test
  464.     generate -- if true, generate output, instead of running the test
  465.     and comparing it to a previously created output file
  466.     verbose -- if true, print more messages
  467.     quiet -- if true, don't print 'skipped' messages (probably redundant)
  468.     testdir -- test directory
  469.     """
  470.     test_support.unload(test)
  471.     if not testdir:
  472.         testdir = findtestdir()
  473.     outputdir = os.path.join(testdir, "output")
  474.     outputfile = os.path.join(outputdir, test)
  475.     if verbose:
  476.         cfp = None
  477.     else:
  478.         cfp = cStringIO.StringIO()
  479.     if huntrleaks:
  480.         refrep = open(huntrleaks[2], "a")
  481.     try:
  482.         save_stdout = sys.stdout
  483.         try:
  484.             if cfp:
  485.                 sys.stdout = cfp
  486.                 print test              # Output file starts with test name
  487.             if test.startswith('test.'):
  488.                 abstest = test
  489.             else:
  490.                 # Always import it from the test package
  491.                 abstest = 'test.' + test
  492.             the_package = __import__(abstest, globals(), locals(), [])
  493.             the_module = getattr(the_package, test)
  494.             # Most tests run to completion simply as a side-effect of
  495.             # being imported.  For the benefit of tests that can't run
  496.             # that way (like test_threaded_import), explicitly invoke
  497.             # their test_main() function (if it exists).
  498.             indirect_test = getattr(the_module, "test_main", None)
  499.             if indirect_test is not None:
  500.                 indirect_test()
  501.             if huntrleaks:
  502.                 # This code *is* hackish and inelegant, yes.
  503.                 # But it seems to do the job.
  504.                 import copy_reg
  505.                 fs = warnings.filters[:]
  506.                 ps = copy_reg.dispatch_table.copy()
  507.                 pic = sys.path_importer_cache.copy()
  508.                 import gc
  509.                 def cleanup():
  510.                     import _strptime, urlparse, warnings, dircache
  511.                     from distutils.dir_util import _path_created
  512.                     _path_created.clear()
  513.                     warnings.filters[:] = fs
  514.                     gc.collect()
  515.                     sre.purge()
  516.                     _strptime._regex_cache.clear()
  517.                     urlparse.clear_cache()
  518.                     copy_reg.dispatch_table.clear()
  519.                     copy_reg.dispatch_table.update(ps)
  520.                     sys.path_importer_cache.clear()
  521.                     sys.path_importer_cache.update(pic)
  522.                     dircache.reset()
  523.                 if indirect_test:
  524.                     def run_the_test():
  525.                         indirect_test()
  526.                 else:
  527.                     def run_the_test():
  528.                         reload(the_module)
  529.                 deltas = []
  530.                 repcount = huntrleaks[0] + huntrleaks[1]
  531.                 print >> sys.stderr, "beginning", repcount, "repetitions"
  532.                 print >> sys.stderr, \
  533.                       ("1234567890"*(repcount//10 + 1))[:repcount]
  534.                 for i in range(repcount):
  535.                     rc = sys.gettotalrefcount()
  536.                     run_the_test()
  537.                     sys.stderr.write('.')
  538.                     cleanup()
  539.                     deltas.append(sys.gettotalrefcount() - rc - 2)
  540.                 print >>sys.stderr
  541.                 if max(map(abs, deltas[-huntrleaks[1]:])) > 0:
  542.                     print >>sys.stderr, test, 'leaked', \
  543.                           deltas[-huntrleaks[1]:], 'references'
  544.                     print >>refrep, test, 'leaked', \
  545.                           deltas[-huntrleaks[1]:], 'references'
  546.                 # The end of the huntrleaks hackishness.
  547.         finally:
  548.             sys.stdout = save_stdout
  549.     except test_support.ResourceDenied, msg:
  550.         if not quiet:
  551.             print test, "skipped --", msg
  552.             sys.stdout.flush()
  553.         return -2
  554.     except (ImportError, test_support.TestSkipped), msg:
  555.         if not quiet:
  556.             print test, "skipped --", msg
  557.             sys.stdout.flush()
  558.         return -1
  559.     except KeyboardInterrupt:
  560.         raise
  561.     except test_support.TestFailed, msg:
  562.         print "test", test, "failed --", msg
  563.         sys.stdout.flush()
  564.         return 0
  565.     except:
  566.         type, value = sys.exc_info()[:2]
  567.         print "test", test, "crashed --", str(type) + ":", value
  568.         sys.stdout.flush()
  569.         if verbose:
  570.             traceback.print_exc(file=sys.stdout)
  571.             sys.stdout.flush()
  572.         return 0
  573.     else:
  574.         if not cfp:
  575.             return 1
  576.         output = cfp.getvalue()
  577.         if generate:
  578.             if output == test + "\n":
  579.                 if os.path.exists(outputfile):
  580.                     # Write it since it already exists (and the contents
  581.                     # may have changed), but let the user know it isn't
  582.                     # needed:
  583.                     print "output file", outputfile, \
  584.                           "is no longer needed; consider removing it"
  585.                 else:
  586.                     # We don't need it, so don't create it.
  587.                     return 1
  588.             fp = open(outputfile, "w")
  589.             fp.write(output)
  590.             fp.close()
  591.             return 1
  592.         if os.path.exists(outputfile):
  593.             fp = open(outputfile, "r")
  594.             expected = fp.read()
  595.             fp.close()
  596.         else:
  597.             expected = test + "\n"
  598.         if output == expected or huntrleaks:
  599.             return 1
  600.         print "test", test, "produced unexpected output:"
  601.         sys.stdout.flush()
  602.         reportdiff(expected, output)
  603.         sys.stdout.flush()
  604.         return 0
  605.  
  606. def reportdiff(expected, output):
  607.     import difflib
  608.     print "*" * 70
  609.     a = expected.splitlines(1)
  610.     b = output.splitlines(1)
  611.     sm = difflib.SequenceMatcher(a=a, b=b)
  612.     tuples = sm.get_opcodes()
  613.  
  614.     def pair(x0, x1):
  615.         # x0:x1 are 0-based slice indices; convert to 1-based line indices.
  616.         x0 += 1
  617.         if x0 >= x1:
  618.             return "line " + str(x0)
  619.         else:
  620.             return "lines %d-%d" % (x0, x1)
  621.  
  622.     for op, a0, a1, b0, b1 in tuples:
  623.         if op == 'equal':
  624.             pass
  625.  
  626.         elif op == 'delete':
  627.             print "***", pair(a0, a1), "of expected output missing:"
  628.             for line in a[a0:a1]:
  629.                 print "-", line,
  630.  
  631.         elif op == 'replace':
  632.             print "*** mismatch between", pair(a0, a1), "of expected", \
  633.                   "output and", pair(b0, b1), "of actual output:"
  634.             for line in difflib.ndiff(a[a0:a1], b[b0:b1]):
  635.                 print line,
  636.  
  637.         elif op == 'insert':
  638.             print "***", pair(b0, b1), "of actual output doesn't appear", \
  639.                   "in expected output after line", str(a1)+":"
  640.             for line in b[b0:b1]:
  641.                 print "+", line,
  642.  
  643.         else:
  644.             print "get_opcodes() returned bad tuple?!?!", (op, a0, a1, b0, b1)
  645.  
  646.     print "*" * 70
  647.  
  648. def findtestdir():
  649.     if __name__ == '__main__':
  650.         file = sys.argv[0]
  651.     else:
  652.         file = __file__
  653.     testdir = os.path.dirname(file) or os.curdir
  654.     return testdir
  655.  
  656. def removepy(name):
  657.     if name.endswith(os.extsep + "py"):
  658.         name = name[:-3]
  659.     return name
  660.  
  661. def count(n, word):
  662.     if n == 1:
  663.         return "%d %s" % (n, word)
  664.     else:
  665.         return "%d %ss" % (n, word)
  666.  
  667. def printlist(x, width=70, indent=4):
  668.     """Print the elements of iterable x to stdout.
  669.  
  670.     Optional arg width (default 70) is the maximum line length.
  671.     Optional arg indent (default 4) is the number of blanks with which to
  672.     begin each line.
  673.     """
  674.  
  675.     from textwrap import fill
  676.     blanks = ' ' * indent
  677.     print fill(' '.join(map(str, x)), width,
  678.                initial_indent=blanks, subsequent_indent=blanks)
  679.  
  680. # Map sys.platform to a string containing the basenames of tests
  681. # expected to be skipped on that platform.
  682. #
  683. # Special cases:
  684. #     test_pep277
  685. #         The _ExpectedSkips constructor adds this to the set of expected
  686. #         skips if not os.path.supports_unicode_filenames.
  687. #     test_normalization
  688. #         Whether a skip is expected here depends on whether a large test
  689. #         input file has been downloaded.  test_normalization.skip_expected
  690. #         controls that.
  691. #     test_socket_ssl
  692. #         Controlled by test_socket_ssl.skip_expected.  Requires the network
  693. #         resource, and a socket module with ssl support.
  694. #     test_timeout
  695. #         Controlled by test_timeout.skip_expected.  Requires the network
  696. #         resource and a socket module.
  697. #     test_codecmaps_*
  698. #         Whether a skip is expected here depends on whether a large test
  699. #         input file has been downloaded.  test_codecmaps_*.skip_expected
  700. #         controls that.
  701.  
  702. _expectations = {
  703.     'win32':
  704.         """
  705.         test__locale
  706.         test_applesingle
  707.         test_al
  708.         test_bsddb185
  709.         test_bsddb3
  710.         test_cd
  711.         test_cl
  712.         test_commands
  713.         test_crypt
  714.         test_curses
  715.         test_dbm
  716.         test_dl
  717.         test_fcntl
  718.         test_fork1
  719.         test_gdbm
  720.         test_gl
  721.         test_grp
  722.         test_imgfile
  723.         test_ioctl
  724.         test_largefile
  725.         test_linuxaudiodev
  726.         test_mhlib
  727.         test_nis
  728.         test_openpty
  729.         test_ossaudiodev
  730.         test_poll
  731.         test_posix
  732.         test_pty
  733.         test_pwd
  734.         test_resource
  735.         test_signal
  736.         test_sunaudiodev
  737.         test_threadsignals
  738.         test_timing
  739.         """,
  740.     'linux2':
  741.         """
  742.         test_al
  743.         test_applesingle
  744.         test_bsddb185
  745.         test_cd
  746.         test_cl
  747.         test_curses
  748.         test_dl
  749.         test_gl
  750.         test_imgfile
  751.         test_largefile
  752.         test_linuxaudiodev
  753.         test_nis
  754.         test_ntpath
  755.         test_ossaudiodev
  756.         test_sunaudiodev
  757.         """,
  758.    'mac':
  759.         """
  760.         test_al
  761.         test_atexit
  762.         test_bsddb
  763.         test_bsddb185
  764.         test_bsddb3
  765.         test_bz2
  766.         test_cd
  767.         test_cl
  768.         test_commands
  769.         test_crypt
  770.         test_curses
  771.         test_dbm
  772.         test_dl
  773.         test_fcntl
  774.         test_fork1
  775.         test_gl
  776.         test_grp
  777.         test_ioctl
  778.         test_imgfile
  779.         test_largefile
  780.         test_linuxaudiodev
  781.         test_locale
  782.         test_mmap
  783.         test_nis
  784.         test_ntpath
  785.         test_openpty
  786.         test_ossaudiodev
  787.         test_poll
  788.         test_popen
  789.         test_popen2
  790.         test_posix
  791.         test_pty
  792.         test_pwd
  793.         test_resource
  794.         test_signal
  795.         test_sunaudiodev
  796.         test_sundry
  797.         test_tarfile
  798.         test_timing
  799.         """,
  800.     'unixware7':
  801.         """
  802.         test_al
  803.         test_applesingle
  804.         test_bsddb
  805.         test_bsddb185
  806.         test_cd
  807.         test_cl
  808.         test_dl
  809.         test_gl
  810.         test_imgfile
  811.         test_largefile
  812.         test_linuxaudiodev
  813.         test_minidom
  814.         test_nis
  815.         test_ntpath
  816.         test_openpty
  817.         test_pyexpat
  818.         test_sax
  819.         test_sunaudiodev
  820.         test_sundry
  821.         """,
  822.     'openunix8':
  823.         """
  824.         test_al
  825.         test_applesingle
  826.         test_bsddb
  827.         test_bsddb185
  828.         test_cd
  829.         test_cl
  830.         test_dl
  831.         test_gl
  832.         test_imgfile
  833.         test_largefile
  834.         test_linuxaudiodev
  835.         test_minidom
  836.         test_nis
  837.         test_ntpath
  838.         test_openpty
  839.         test_pyexpat
  840.         test_sax
  841.         test_sunaudiodev
  842.         test_sundry
  843.         """,
  844.     'sco_sv3':
  845.         """
  846.         test_al
  847.         test_applesingle
  848.         test_asynchat
  849.         test_bsddb
  850.         test_bsddb185
  851.         test_cd
  852.         test_cl
  853.         test_dl
  854.         test_fork1
  855.         test_gettext
  856.         test_gl
  857.         test_imgfile
  858.         test_largefile
  859.         test_linuxaudiodev
  860.         test_locale
  861.         test_minidom
  862.         test_nis
  863.         test_ntpath
  864.         test_openpty
  865.         test_pyexpat
  866.         test_queue
  867.         test_sax
  868.         test_sunaudiodev
  869.         test_sundry
  870.         test_thread
  871.         test_threaded_import
  872.         test_threadedtempfile
  873.         test_threading
  874.         """,
  875.     'riscos':
  876.         """
  877.         test_al
  878.         test_applesingle
  879.         test_asynchat
  880.         test_atexit
  881.         test_bsddb
  882.         test_bsddb185
  883.         test_bsddb3
  884.         test_cd
  885.         test_cl
  886.         test_commands
  887.         test_crypt
  888.         test_dbm
  889.         test_dl
  890.         test_fcntl
  891.         test_fork1
  892.         test_gdbm
  893.         test_gl
  894.         test_grp
  895.         test_imgfile
  896.         test_largefile
  897.         test_linuxaudiodev
  898.         test_locale
  899.         test_mmap
  900.         test_nis
  901.         test_ntpath
  902.         test_openpty
  903.         test_poll
  904.         test_popen2
  905.         test_pty
  906.         test_pwd
  907.         test_strop
  908.         test_sunaudiodev
  909.         test_sundry
  910.         test_thread
  911.         test_threaded_import
  912.         test_threadedtempfile
  913.         test_threading
  914.         test_timing
  915.         """,
  916.     'darwin':
  917.         """
  918.         test__locale
  919.         test_al
  920.         test_bsddb
  921.         test_bsddb3
  922.         test_cd
  923.         test_cl
  924.         test_curses
  925.         test_dl
  926.         test_gdbm
  927.         test_gl
  928.         test_imgfile
  929.         test_largefile
  930.         test_linuxaudiodev
  931.         test_locale
  932.         test_minidom
  933.         test_nis
  934.         test_ntpath
  935.         test_ossaudiodev
  936.         test_poll
  937.         test_sunaudiodev
  938.         """,
  939.     'sunos5':
  940.         """
  941.         test_al
  942.         test_applesingle
  943.         test_bsddb
  944.         test_bsddb185
  945.         test_cd
  946.         test_cl
  947.         test_curses
  948.         test_dbm
  949.         test_gdbm
  950.         test_gl
  951.         test_gzip
  952.         test_imgfile
  953.         test_linuxaudiodev
  954.         test_openpty
  955.         test_zipfile
  956.         test_zlib
  957.         """,
  958.     'hp-ux11':
  959.         """
  960.         test_al
  961.         test_applesingle
  962.         test_bsddb
  963.         test_bsddb185
  964.         test_cd
  965.         test_cl
  966.         test_curses
  967.         test_dl
  968.         test_gdbm
  969.         test_gl
  970.         test_gzip
  971.         test_imgfile
  972.         test_largefile
  973.         test_linuxaudiodev
  974.         test_locale
  975.         test_minidom
  976.         test_nis
  977.         test_ntpath
  978.         test_openpty
  979.         test_pyexpat
  980.         test_sax
  981.         test_sunaudiodev
  982.         test_zipfile
  983.         test_zlib
  984.         """,
  985.     'atheos':
  986.         """
  987.         test_al
  988.         test_applesingle
  989.         test_bsddb185
  990.         test_cd
  991.         test_cl
  992.         test_curses
  993.         test_dl
  994.         test_gdbm
  995.         test_gl
  996.         test_imgfile
  997.         test_largefile
  998.         test_linuxaudiodev
  999.         test_locale
  1000.         test_mhlib
  1001.         test_mmap
  1002.         test_nis
  1003.         test_poll
  1004.         test_popen2
  1005.         test_resource
  1006.         test_sunaudiodev
  1007.         """,
  1008.     'cygwin':
  1009.         """
  1010.         test_al
  1011.         test_applesingle
  1012.         test_bsddb185
  1013.         test_bsddb3
  1014.         test_cd
  1015.         test_cl
  1016.         test_curses
  1017.         test_dbm
  1018.         test_gl
  1019.         test_imgfile
  1020.         test_ioctl
  1021.         test_largefile
  1022.         test_linuxaudiodev
  1023.         test_locale
  1024.         test_nis
  1025.         test_ossaudiodev
  1026.         test_socketserver
  1027.         test_sunaudiodev
  1028.         """,
  1029.     'os2emx':
  1030.         """
  1031.         test_al
  1032.         test_applesingle
  1033.         test_audioop
  1034.         test_bsddb185
  1035.         test_bsddb3
  1036.         test_cd
  1037.         test_cl
  1038.         test_commands
  1039.         test_curses
  1040.         test_dl
  1041.         test_gl
  1042.         test_imgfile
  1043.         test_largefile
  1044.         test_linuxaudiodev
  1045.         test_mhlib
  1046.         test_mmap
  1047.         test_nis
  1048.         test_openpty
  1049.         test_ossaudiodev
  1050.         test_pty
  1051.         test_resource
  1052.         test_signal
  1053.         test_sunaudiodev
  1054.         """,
  1055.     'freebsd4':
  1056.         """
  1057.         test_aepack
  1058.         test_al
  1059.         test_applesingle
  1060.         test_bsddb
  1061.         test_bsddb3
  1062.         test_cd
  1063.         test_cl
  1064.         test_gdbm
  1065.         test_gl
  1066.         test_imgfile
  1067.         test_linuxaudiodev
  1068.         test_locale
  1069.         test_macfs
  1070.         test_macostools
  1071.         test_nis
  1072.         test_normalization
  1073.         test_ossaudiodev
  1074.         test_pep277
  1075.         test_plistlib
  1076.         test_pty
  1077.         test_scriptpackages
  1078.         test_socket_ssl
  1079.         test_socketserver
  1080.         test_sunaudiodev
  1081.         test_tcl
  1082.         test_timeout
  1083.         test_unicode_file
  1084.         test_urllibnet
  1085.         test_winreg
  1086.         test_winsound
  1087.         """,
  1088.     'aix5':
  1089.         """
  1090.         test_aepack
  1091.         test_al
  1092.         test_applesingle
  1093.         test_bsddb
  1094.         test_bsddb185
  1095.         test_bsddb3
  1096.         test_bz2
  1097.         test_cd
  1098.         test_cl
  1099.         test_dl
  1100.         test_gdbm
  1101.         test_gl
  1102.         test_gzip
  1103.         test_imgfile
  1104.         test_linuxaudiodev
  1105.         test_macfs
  1106.         test_macostools
  1107.         test_nis
  1108.         test_ossaudiodev
  1109.         test_sunaudiodev
  1110.         test_tcl
  1111.         test_winreg
  1112.         test_winsound
  1113.         test_zipimport
  1114.         test_zlib
  1115.         """,
  1116. }
  1117. _expectations['freebsd5'] = _expectations['freebsd4']
  1118. _expectations['freebsd6'] = _expectations['freebsd4']
  1119.  
  1120. class _ExpectedSkips:
  1121.     def __init__(self):
  1122.         import os.path
  1123.         from test import test_normalization
  1124.         from test import test_socket_ssl
  1125.         from test import test_timeout
  1126.         from test import test_codecmaps_cn, test_codecmaps_jp
  1127.         from test import test_codecmaps_kr, test_codecmaps_tw
  1128.         from test import test_codecmaps_hk
  1129.  
  1130.         self.valid = False
  1131.         if sys.platform in _expectations:
  1132.             s = _expectations[sys.platform]
  1133.             self.expected = set(s.split())
  1134.  
  1135.             if not os.path.supports_unicode_filenames:
  1136.                 self.expected.add('test_pep277')
  1137.  
  1138.             if test_normalization.skip_expected:
  1139.                 self.expected.add('test_normalization')
  1140.  
  1141.             if test_socket_ssl.skip_expected:
  1142.                 self.expected.add('test_socket_ssl')
  1143.  
  1144.             if test_timeout.skip_expected:
  1145.                 self.expected.add('test_timeout')
  1146.  
  1147.             for cc in ('cn', 'jp', 'kr', 'tw', 'hk'):
  1148.                 if eval('test_codecmaps_' + cc).skip_expected:
  1149.                     self.expected.add('test_codecmaps_' + cc)
  1150.  
  1151.             if sys.maxint == 9223372036854775807L:
  1152.                 self.expected.add('test_rgbimg')
  1153.                 self.expected.add('test_imageop')
  1154.  
  1155.             if not sys.platform in ("mac", "darwin"):
  1156.                 MAC_ONLY = ["test_macostools", "test_macfs", "test_aepack",
  1157.                             "test_plistlib", "test_scriptpackages"]
  1158.                 for skip in MAC_ONLY:
  1159.                     self.expected.add(skip)
  1160.  
  1161.             if sys.platform != "win32":
  1162.                 WIN_ONLY = ["test_unicode_file", "test_winreg",
  1163.                             "test_winsound"]
  1164.                 for skip in WIN_ONLY:
  1165.                     self.expected.add(skip)
  1166.  
  1167.             self.valid = True
  1168.  
  1169.     def isvalid(self):
  1170.         "Return true iff _ExpectedSkips knows about the current platform."
  1171.         return self.valid
  1172.  
  1173.     def getexpected(self):
  1174.         """Return set of test names we expect to skip on current platform.
  1175.  
  1176.         self.isvalid() must be true.
  1177.         """
  1178.  
  1179.         assert self.isvalid()
  1180.         return self.expected
  1181.  
  1182. if __name__ == '__main__':
  1183.     # Remove regrtest.py's own directory from the module search path.  This
  1184.     # prevents relative imports from working, and relative imports will screw
  1185.     # up the testing framework.  E.g. if both test.test_support and
  1186.     # test_support are imported, they will not contain the same globals, and
  1187.     # much of the testing framework relies on the globals in the
  1188.     # test.test_support module.
  1189.     mydir = os.path.abspath(os.path.normpath(os.path.dirname(sys.argv[0])))
  1190.     i = pathlen = len(sys.path)
  1191.     while i >= 0:
  1192.         i -= 1
  1193.         if os.path.abspath(os.path.normpath(sys.path[i])) == mydir:
  1194.             del sys.path[i]
  1195.     if len(sys.path) == pathlen:
  1196.         print 'Could not find %r in sys.path to remove it' % mydir
  1197.     main()
  1198.